use sea_orm::{ActiveModelBehavior, ActiveValue, DatabaseConnection, EntityTrait, IntoActiveModel};
use sky_pojo::{dto::shopping::ShoppingCartDTO, entities::shopping_cart};

use crate::mapper;
pub async fn add_shopping_cart(
    db: &DatabaseConnection,
    user_id: i64,
    dto: ShoppingCartDTO,
) -> Result<shopping_cart::Model, String> {
    let shopping_cart_model = shopping_cart::ActiveModel {
        // 只能查询自己的购物车数据
        user_id: sea_orm::ActiveValue::set(user_id),
        dish_id: sea_orm::ActiveValue::set(dto.dish_id),
        dish_flavor: sea_orm::ActiveValue::set(dto.dish_flavor),
        setmeal_id: sea_orm::ActiveValue::set(dto.setmeal_id),
        // number: sea_orm::ActiveValue::set(1),
        ..Default::default()
    };

    // Clone the model before passing to list to avoid ownership issue
    let shopping_cart_model_clone = shopping_cart_model.clone();

    let shopping_cart_list =
        mapper::shoppingcart::list(db.clone(), shopping_cart_model_clone).await;



    match shopping_cart_list {
        Ok(mut items) if !items.is_empty() => {
            tracing::debug!("{:?}", items.clone());
            let mut existing_cart = items.remove(0);
            // 如果已经存在，就更新数量，数量加1
            existing_cart.number = existing_cart.number + 1;

            mapper::shoppingcart::update_number_by_id(db.clone(), existing_cart.into())
                .await
                .map_err(|e| e.to_string())
        }
        _ => {
            // 判断当前添加到购物车的是菜品还是套餐
            let mut model_clone = shopping_cart_model.clone();
            if let Some(dish_id) = dto.dish_id {
                // 菜品
                match mapper::dish::find_by_id(db.clone(), dish_id).await {
                    Ok(dish) => {
                        model_clone.name = ActiveValue::set(Some(dish.name));
                        model_clone.image = ActiveValue::set(dish.image);
                        model_clone.amount = ActiveValue::set(dish.price.unwrap());
                    }
                    Err(e) => return Err(e.to_string()),
                }
            } else if let Some(setmeal_id) = dto.setmeal_id {
                // 套餐
                match mapper::setmeal::query_by_id(db.clone(), setmeal_id).await {
                    Ok(setmeal) => {
                        model_clone.name = ActiveValue::set(Some(setmeal.name));
                        model_clone.image = ActiveValue::set(setmeal.image);
                        model_clone.amount = ActiveValue::set(setmeal.price);
                    }
                    Err(e) => return Err(e.to_string()),
                }
            }

            match mapper::shoppingcart::insert(db.clone(), model_clone).await {
                Ok(model) => Ok(model),
                Err(e) => Err(e.to_string()),
            }
        }
    }
}

pub async fn list(
    db: &DatabaseConnection,
    user_id: i64,
) -> Result<Vec<shopping_cart::Model>, String> {
    match mapper::shoppingcart::list(
        db.clone(),
        shopping_cart::ActiveModel {
            user_id: ActiveValue::set(user_id),
            ..Default::default()
        },
    )
    .await
    {
        Ok(vec) => Ok(vec),
        Err(e) => Err(e.to_string()),
    }
}

pub async fn clean_shopping_cart(db: &DatabaseConnection, user_id: i64) -> Result<u64, String> {
    match mapper::shoppingcart::delete_by_user_id(db, user_id).await {
        Ok(res) => Ok(res.rows_affected),
        Err(e) => Err(e.to_string()),
    }
}

pub async fn sub_shoppingcart(db: &DatabaseConnection, dto: ShoppingCartDTO, user_id: i64) {
    let mut cart = shopping_cart::ActiveModel {
        user_id: sea_orm::ActiveValue::set(user_id),
        dish_id: sea_orm::ActiveValue::set(dto.dish_id),
        setmeal_id: sea_orm::ActiveValue::set(dto.setmeal_id),
        dish_flavor: sea_orm::ActiveValue::set(dto.dish_flavor),
        ..Default::default()
    };

    match mapper::shoppingcart::list(db.clone(), cart).await {
        Ok(mut vec) => {
            if vec.len() > 0 && !vec.is_empty() {
                if let Some(model) = vec.first_mut() {
                    if model.number == 1 {
                        mapper::shoppingcart::delete_by_id(db, model.id).await;
                    } else {
                        model.number -= 1;
                        mapper::shoppingcart::update_number_by_id(
                            db.clone(),
                            model.clone().into_active_model(),
                        )
                        .await
                        .unwrap();
                    }
                }
            }
        }
        Err(_) => (),
    }
}
